/*
 * @Author: qianduanxuyaochendian lxy_01@outlook.com
 * @Date: 2022-05-19 16:35:29
 * @LastEditors: qianduanxuyaochendian lxy_01@outlook.com
 * @LastEditTime: 2022-05-24 23:06:43
 * @FilePath: \job\server\router\companyRouter.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 引入expres
const express = require("express")
// 引入路由模块
const router = express.Router()
// 引入数据库
const connection = require("../db/sql.js")
// 引入时间处理插件
const moment = require("moment")

// 引入图片上传工具
const upload = require("../utils/upload.js")

// 引入token验证模块
const { verifyToken } = require("../config/token.js")

const { ERROR_MSG } = require("../config/global")

// 引入nodemailer模块
const nodemailer = require("nodemailer")

//配置邮件传送服务
let mailTransport = nodemailer.createTransport({
  // host: 'smtp.qq.email',
  service: "qq",
  secure: true, //安全方式发送,建议都加上
  auth: {
    user: "508244550@qq.com", //配置中的auth用于配置用于发送邮件的邮箱,这里使用的是qq邮箱
    pass: "hczsljkxbukqbgia",
  },
})

// 公司注册接口
const cpUpload = upload.fields([
  {
    name: "logo",
    maxCount: 1,
  },
  {
    name: "cpPhotos",
    maxCount: 8,
  },
])
router.post("/register", cpUpload, (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  const company = req.body
  // console.log(req.files.logo[0].path.replaceAll('\\','/'));
  // console.log(company.about);
  const asyncRequest = []
  const registerCompanySQL = `INSERT INTO s_company VALUES (NULL,${
    userInfo.id
  },'${req.files.logo ? req.files.logo[0].path.replaceAll("\\", "/") : ""}','${
    company.name
  }','${company.email}','${company.tel}','${company.website}','${moment(
    company.creation_date / 1
  ).format("YYYY-MM-DD")}',${company.size},'${
    company.address
  }','${company.about.replaceAll("'", '"')}','${moment().format(
    "YYYY-MM-DD HH:mm:ss"
  )}');`

  // console.log(registerCompanySQL)

  // 先存储公司信息，再根据存储的公司的ID来存储关联的公司插图信息
  connection.query(registerCompanySQL, (err, result) => {
    if (err) {
      res.reply_error(ERROR_MSG.UNKNOWN_ERROR, err.message)
    }

    if (req.files.cpPhotos) {
      req.files.cpPhotos.forEach((p) => {
        asyncRequest.push(
          new Promise((resolve, reject) => {
            let addCompanyPictureSQL = `INSERT INTO s_company_picture VALUES (NULL,${
              result.insertId
            },'${p.path.replaceAll("\\", "/")}')`
            connection.query(addCompanyPictureSQL, (e, r) => {
              if (r.length > 0) {
                resolve()
              }
            })
          })
        )
      })

      Promise.all(asyncRequest).then((resultAll) => {
        res.reply_success()
      })
    } else {
      res.reply_success()
    }
  })
})

// 获取公司信息卡片数据接口
router.get("/companySimpleInfo", (req, res) => {
  const sql = "select id,logo,name from s_company"
  connection.query(sql, (err, result) => {
    if (result) {
      //   res.send(JSON.stringify(result))
      res.reply_success(result)
    } else {
      console.log(err.message)
    }
  })
})

// 获取公司详细信息数据接口
router.get("/companyInfo", (req, res) => {
  const companyId = req.query.id
  const companyInfoSQL = `select * from s_company WHERE id = ${companyId}`
  connection.query(companyInfoSQL, (err, result) => {
    if (result) {
      const backData = result[0]
      const childSearch = []
      // 查询关联图
      childSearch.push(
        new Promise((resolve, reject) => {
          const companyPicturesSQL = `select img_url from s_company_picture where company_id = ${companyId}`
          connection.query(companyPicturesSQL, (err, result) => {
            backData["pictures"] = result
            resolve()
          })
        })
      )

      // 查询关联职位
      childSearch.push(
        new Promise((resolve, reject) => {
          const companyJobsSQL = `select id,name,city,status,create_time from s_job where c_id = ${companyId}`
          connection.query(companyJobsSQL, (err, result) => {
            backData["jobs"] = result
            resolve()
          })
        })
      )

      Promise.all(childSearch).then((result) => {
        res.reply_success(backData)
      })

      // res.reply_success(backData)
    } else {
      console.log(err.message)
    }
  })
})

// 获取公司列表数据的接口
router.get("/getCompanyList", (req, res) => {
  const sql = "select * from s_company"
  connection.query(sql, (err, result) => {
    if (result) {
      //   res.send(JSON.stringify(result))
      res.reply_success(result)
    } else {
      console.log(err.message)
    }
  })
})

// 获取职位列表数据的接口
router.get("/getJobList", (req, res) => {
  const sql = `select * from s_job`
  connection.query(sql, (err, result) => {
    if (result) {
      let p = []
      //查询关联公司名称,公司logo
      for (let i = 0; i < result.length; i++) {
        const companyNameSql = `select name,logo from s_company where id =${result[i]["c_id"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(companyNameSql, (err, results) => {
              if (results.length > 0) {
                // let data = []
                // data.push(results)
                // console.log(results[0]["name"])
                result[i]["cname"] = results[0]["name"]
                result[i]["logo"] = results[0]["logo"]
                resolve()
              }
            })
          })
        )
      }

      // 查询关联学历要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type FROM d_education WHERE id =${result[i]["education"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["academic"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      //关联工作经验要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type  from d_job_experience WHERE id  =${result[i]["experience"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["experienceRequire"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      //关联工作福利列表
      for (let i = 0; i < result.length; i++) {
        const welfareSql = `SELECT tag  from s_job WHERE id  =${result[i]["id"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(welfareSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["welfare"] = {
                  type: JSON.parse(results[0]["tag"]).join(",").split(","),
                }
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      Promise.all(p).then((data) => {
        res.reply_success(result)
      })
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})
//获取工作详情
router.post("/getDetail", (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  const jid = req.body.id
  const sql = `select * from s_job where id = ${jid}`
  connection.query(sql, (err, result) => {
    if (result) {
      let p = []
      //查询关联公司名称,公司logo
      for (let i = 0; i < result.length; i++) {
        const companyNameSql = `select name,logo from s_company where id =${result[i]["c_id"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(companyNameSql, (err, results) => {
              if (results.length > 0) {
                // let data = []
                // data.push(results)
                // console.log(results[0]["name"])
                result[i]["cname"] = results[0]["name"]
                result[i]["logo"] = results[0]["logo"]
                resolve()
              }
            })
          })
        )
      }

      // 查询关联学历要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type FROM d_education WHERE id =${result[i]["education"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["academic"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      //关联工作经验要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type  from d_job_experience WHERE id  =${result[i]["experience"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["experienceRequire"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      //关联工作福利列表
      // for (let i = 0; i < result.length; i++) {
      //   const educationSql = `SELECT type  from d_job_experience WHERE id  =${result[i]["experience"]}`
      //   p.push(
      //     new Promise((resolve, reject) => {
      //       connection.query(educationSql, (err, results) => {
      //         if (results.length > 0) {
      //           // console.log(results[0]["type"])
      //           result[i]["experienceRequire"] = results[0]["type"]
      //           // console.log(results[0]["type"])
      //           resolve()
      //         }
      //       })
      //     })
      //   )
      // }
      Promise.all(p).then((data) => {
        res.reply_success(result)
      })
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//获取分类列表
router.get("/loadList", (req, res) => {
  const sql = `SELECT * from d_job_type`
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

// 获取职位分类数据
router.post("/getCategoryList", (req, res) => {
  // const type = req.body.type
  const sql = `select * from s_job where type = ${req.body.tid}`
  connection.query(sql, (err, result) => {
    if (result) {
      let p = []
      //查询关联公司名称,公司logo
      for (let i = 0; i < result.length; i++) {
        const companyNameSql = `select name,logo from s_company where id =${result[i]["c_id"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(companyNameSql, (err, results) => {
              if (results.length > 0) {
                // let data = []
                // data.push(results)
                // console.log(results[0]["name"])
                result[i]["cname"] = results[0]["name"]
                result[i]["logo"] = results[0]["logo"]
                resolve()
              }
            })
          })
        )
      }

      // 查询关联学历要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type FROM d_education WHERE id =${result[i]["education"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["academic"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      //关联工作经验要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type  from d_job_experience WHERE id  =${result[i]["experience"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["experienceRequire"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      Promise.all(p).then((data) => {
        res.reply_success(result)
      })
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//获取公司头像接口
router.post("/obtainAvatar", (req, res) => {
  const cid = req.body.cid
  const sql = `select logo,name from s_company where id = ${cid}`
  // console.log(req.body.cid)
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//首页搜索功能接口
router.post("/search", (req, res) => {
  const jname = req.body.name
  const jcity = req.body.city
  const sql = `select * from s_job where name like '%${jname}%' OR city like '%${jcity}%' `
  connection.query(sql, (err, result) => {
    if (result) {
      console.log(result)
      let p = []
      //查询关联公司名称,公司logo
      for (let i = 0; i < result.length; i++) {
        const companyNameSql = `select name,logo from s_company where id =${result[i]["c_id"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(companyNameSql, (err, results) => {
              if (results.length > 0) {
                // let data = []
                // data.push(results)
                // console.log(results[0]["name"])
                result[i]["cname"] = results[0]["name"]
                result[i]["logo"] = results[0]["logo"]
                resolve()
              }
            })
          })
        )
      }

      // 查询关联学历要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type FROM d_education WHERE id =${result[i]["education"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["academic"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }
      //关联工作经验要求
      for (let i = 0; i < result.length; i++) {
        const educationSql = `SELECT type  from d_job_experience WHERE id  =${result[i]["experience"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(educationSql, (err, results) => {
              if (results.length > 0) {
                // console.log(results[0]["type"])
                result[i]["experienceRequire"] = results[0]["type"]
                // console.log(results[0]["type"])
                resolve()
              }
            })
          })
        )
      }

      Promise.all(p).then((data) => {
        res.reply_success(result)
      })
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//用于企业检阅简历(获取学生简历信息)
router.post("/getStudentResume", (req, res) => {
// console.log(req.body);
   let id = req.body.id
  const sql = `select * from s_student where user_id = ${id}`
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//获取公司收到的简历列表
router.post("/getResumeList", (req, res) => {
  // console.log(req.body.id);
  const sql = `SELECT * FROM s_company_resume where company_id =${req.body.id}`
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//发送邮件接口
router.post("/sendEmail", function (req, res) {
  console.log(req.body)
  const sql = `SELECT email from s_student where user_id = ${req.body.id}`
  connection.query(sql, (err, result) => {
    if (result) {
      let options = {
        from: "<508244550@qq.com>",
        to: `< ${result[0].email} >`,
        bcc: "密送",
        subject: "面试通知",
        text: "hello nodemailer",
        html: "<h1>hello nodemailer</h1>",
      }
      mailTransport.sendMail(options, function (err, msg) {
        if (err) {
          res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "发送失败")
        } else {
          //更改学生的简历状态
          const updateSql = `UPDATE s_company_resume set status = 2 where user_id =${req.body.id} AND company_id =? AND  apply_job =?`
          connection.query(
            updateSql,
            [ req.body.cid, req.body.apply_job],
            (err, results) => {
              if (result) {
                res.reply_success({ code: 200 })
              }
            }
          )
        }
      })
    }
  })
})

module.exports = router
